﻿using System;
using System.Collections.Generic;

using Moe.ECamel.Common.Entities;
using Moe.ECamel.Server.BL;

namespace Moe.ECamel.Server.Services
{
	public class SalaryService : ECamelService
	{
		public void GenerateSalaries(DateTime date)
		{
			IList<Employee> employees;
			using (var employeeService = new EmployeeService(this))
			{
				employees = employeeService.GetAllEmployees();
			}

			IList<MailMessage> messages = new List<MailMessage>();

			using (var bl = new SalaryBL(GetReadWriteDataContext()))
			{
				foreach (var employee in employees)
				{
					bool isCreated = bl.CreateSalaryIfNeeded(employee, date);
					if (isCreated)
					{
						var message = new MailMessage();
						message.UserId = employee.UserId;
						message.ToAddress = employee.User.EmailAddress;
						message.SentOn = date;
						message.Subject = "תלוש משכורת לתאריך " + date.ToShortDateString();
						message.Body = "המשכורת שלך עבור חודש זה היא " + employee.Salary + " שקלים חדשים.";
						messages.Add(message);
					}
				}
			}

			using (var mailMessageService = new MailMessageService(this))
			{
				foreach (var message in messages)
					mailMessageService.SendMessage(message);
			}

			SubmitChanges();
		}
	}
}
